class Nodes {
  constructor(element) {
    this.element = element;
    this.next = null;
  }
}

 class LinkList {
  constructor() {
    let head = null;
    let length = 0;
    this.append = (element) => {
      let node = new Nodes(element);
      let current = null;
      if (head == null) {
        head = node;
      } else {
        current = head;
        while (current.next) {
          current = current.next;
        }
        current.next = node;
      }
      length++;
    };

    this.remove = (position) => {
      if (position > -1 && position < length) {
        let current = head,
          previous,
          index = 0;
        if (position == 0) {
          head == current.next;
        } else {
          while (index++ < position) {
            previous = current;
            current = current.next;
          }
          previous.next = current.next;
        }
        length--;
        return current.element;
      } else {
        throw new Error("链表中暂无值");
      }
    };

    this.insertElement = (position, element) => {
      if (position > -1 && position <= length) {
        let node = new Nodes(element);
        let current = head,
          previous,
          index = 0;
        if (position == 0) {
          node.next = current;
          head = node;
        } else {
          while (index++ < position) {
            previous = current;
            current = current.next;
          }
          node.next = current;
          previous.next = node;
        }
        length++;
        return true;
      } else {
        throw new Error("插入错误");
      }
    };

    //返回链表的字符串
    this.toString = () => {
      let current = head,
        stringList = "";
      while (current) {
        stringList +=
          JSON.stringify(current.element) + (current.next ? " => " : "");
        current = current.next;
      }
      return stringList;
    };

    //查找元素
    this.indexOfList = (element) => {
      let current = head,
        index = 0;
      while (current) {
        if (element === current.element) {
          return index;
        }
        index++;
        current = current.next;
      }
      return -1;
    };

    //判空
    this.isEmpty = () => {
      return length === 0;
    };

    //长度
    this.size = () => {
      return length;
    };

    // 找链表头部
    this.getHead = () => {
      return head;
    };
  }
}

let a = new LinkList();
a.append(12);
a.append(12);
a.append(12);
a.append(12);
a.append(12);
a.append(13);
a.append(12);
a.append(12);
// a.append(12);
console.log(a);
a.remove(0);
console.log(a.size());
console.log(a.getHead());
console.log(a.toString());
console.log(a.indexOfList(13));

export default LinkList